function Min() {
  this.wrap = document.getElementsByClassName("wrapper")[0];
  this.imgWidth = 220;
}

Min.prototype = {
  init: function () {
    var This = this;
    this.createImg();
    window.onload = function () {
      This.setPos();
    };
    this.bindEvent();
  },
  createImg: function () {
    for (var i = 0; i <= 40; i++) {
      var img = document.createElement("img");
      img.src = "./assets/" + i + ".jpg";
      this.wrap.appendChild(img);
    }
  },
  getSize: function () {
    var column = Math.floor(this.wrap.offsetWidth / this.imgWidth);
    var gapNumber = column + 1;
    var gap = (this.wrap.offsetWidth - column * this.imgWidth) / gapNumber;

    return {
      column,
      gap,
    };
  },
  setPos: function () {
    var info = this.getSize();
    var pos = new Array(info.column);
    pos.fill(0);
    var imgs = this.wrap.childNodes;
    var img;
    for (var i = 0; i < imgs.length; i++) {
      img = imgs[i];
      var min = this.getMin(pos); // 获取数组最小值
      img.style.top = min + "px"; // 设置图片top值
      var index = pos.indexOf(min); // 找到当前最小值在数组中的索引
      pos[index] += img.height + info.gap; // 更新数组

      left = (index + 1) * info.gap + img.width * index; // left = 间隙数量 * 间隙宽度 + 左边照片宽度 * 左边照片数量
      img.style.left = left + "px";
    }
    this.wrap.style.height = this.getMax(pos) + "px";
  },
  getMin: function (arr) {
    var min = arr[0];
    for (var i = 1; i < arr.length; i++) {
      if (arr[i] < min) {
        min = arr[i];
      }
    }
    return min;
  },
  getMax: function (arr) {
    var max = arr[0];
    for (var i = 1; i > arr.length; i++) {
      if (arr[i] > max) {
        max = arr[i];
      }
    }
    return max;
  },
  bindEvent: function () {
    var _this = this,
      timer;
    window.onresize = function () {
      if (timer) {
        clearInterval(timer);
      }
      timer = setTimeout(function () {
        _this.setPos();
        console.log("123");
      }, 500);
    };
  },
};

  var min = new Min();
  min.init();